#!/usr/bin/env node
const { execSync } = require("child_process");

const taggedPackages = execSync("git tag --points-at HEAD")
  .toString()
  .trim()
  .split("\n");

// anything that matches `-` after MAJOR.MINOR.PATCH
const validPattern = new RegExp(/\d+\.\d+\.\d+-(\w+)/);

// Ensure that all releases use the same prerelease suffix.
// We want to only release all final versions, or all betas etc
const allPrereleaseSuffixes =  taggedPackages.map((version) => {
  const result = validPattern.exec(version);
  return result ? result[1] : '';
});
if ((new Set(allPrereleaseSuffixes)).size > 1) {
  throw Error("All packages must be of the same type of release. Versions cannot be mixed.");
}

// set this using machine.environment.SHIPIT_LERNA_PUBLISH_MECHANISM in your shipit.yml
const publishMechanism = process.env.SHIPIT_LERNA_PUBLISH_MECHANISM || 'from-git';

if (!['from-package', 'from-git'].includes(publishMechanism)) {
  throw Error("SHIPIT_LERNA_PUBLISH_MECHANISM must be 'from-package' or 'from-git'.");
}

const command = [
  "node_modules/.bin/lerna publish",
  publishMechanism,
  "--yes",
  "--dist-tag latest",
  "--pre-dist-tag next",
];

const commandString = command.join(" ");

console.log(`${commandString}`);
execSync(commandString);
